<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试websocket</title>
    <script type="text/javascript">
        var websocket = null;
        function connection() {
            if ("WebSocket" in window) {
                var username = document.getElementById("name").value;
                // 打开一个 web socket
                websocket = new WebSocket("ws://"+document.location.host+"/websocket/"+username);

                websocket.onopen = function () {
                    // Web Socket 已连接上，使用 send() 方法发送数据
                    document.getElementById("message").innerHTML = "建立连接了...";
                };

                websocket.onmessage = function (evt) {
                    var data = evt.data;
                    document.getElementById("message").innerHTML = "数据已接收...,返回消息为: "+data;
                };

                websocket.onclose = function () {
                    // 关闭 websocket
                    document.getElementById("message").innerHTML = "连接已关闭...";
                };

                window.onbeforeunload = function (){
                    //当浏览器关闭的时候,此处应该关联websocket连接,防止服务器出现异常
                   if(websocket != null){
                       websocket.close();
                   }
                }
            } else {
                // 浏览器不支持 WebSocket
                alert("您的浏览器不支持 WebSocket!");
            }
        }
        function sendMessage(){
            //获取发送给谁
            var toUser = document.getElementById("toUser").value;
            //获取发送的内容
            var toMessage = document.getElementById("toMessage").value;
            if (websocket != null) {
                var message = '{"toUser":"'+toUser+'","toMessage":"'+toMessage+'"}';
                websocket.send(message);
            }
        }
    </script>
</head>
<body>
<input type="text" id="name" name="name"/><button  onclick="connection()">建立连接</button><br>
接收者名字:<input type="text" name="toUser" id="toUser"/><br>
接收内容:<input type="text" name="toMessage" id="toMessage"/><br>
<button onclick="sendMessage();">发送</button><br>
<span id="message"></span>
</body>
</html>